package com.eduhzy.ttw.work.mvp.presenter;

import android.app.Application;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.eduhzy.ttw.commonres.utils.RxUtil;
import com.eduhzy.ttw.commonsdk.core.Constants;
import com.eduhzy.ttw.commonsdk.entity.CommonData;
import com.eduhzy.ttw.commonsdk.entity.MineClassData;
import com.eduhzy.ttw.commonsdk.entity.UploadData;
import com.eduhzy.ttw.work.mvp.contract.PublishWorkContract;
import com.eduhzy.ttw.work.mvp.model.entity.WorkSubmitData;
import com.jess.arms.di.scope.ActivityScope;
import com.jess.arms.http.imageloader.ImageLoader;
import com.jess.arms.integration.AppManager;
import com.jess.arms.mvp.BasePresenter;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.RxLifecycleUtils;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import me.jessyan.rxerrorhandler.core.RxErrorHandler;
import me.jessyan.rxerrorhandler.handler.ErrorHandleSubscriber;


/**
 * @author xubo
 * @date 2018-12-3 10:07:39
 */
@ActivityScope
public class PublishWorkPresenter extends BasePresenter<PublishWorkContract.Model, PublishWorkContract.View> {
    @Inject
    RxErrorHandler mErrorHandler;
    @Inject
    Application mApplication;
    @Inject
    ImageLoader mImageLoader;
    @Inject
    AppManager mAppManager;

    @Inject
    public PublishWorkPresenter(PublishWorkContract.Model model, PublishWorkContract.View rootView) {
        super(model, rootView);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        this.mErrorHandler = null;
        this.mAppManager = null;
        this.mImageLoader = null;
        this.mApplication = null;
    }


    public void create(String title, String content
            , StringBuilder imageIds
            , StringBuilder audioIds
            , StringBuilder videoIds
            , long endTime
            , StringBuilder classIds
            , int online) {

        QMUITipDialog tipDialog = RxUtil.showLoading(mRootView.getActivity(), "正在发布···");
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("title", title);
        map.put("content", content);
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        if (ObjectUtils.isNotEmpty(imageIds)) {
            map.put("imageIds", imageIds);
        }
        if (ObjectUtils.isNotEmpty(audioIds)) {
            map.put("audioIds", audioIds);
        }
        if (ObjectUtils.isNotEmpty(videoIds)) {
            map.put("videoIds", videoIds);
        }
        map.put("endTime", endTime);
        map.put("classIds", classIds.toString());
        map.put("online", online);
        //隐藏下拉刷新的进度条
        mModel.create(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    //显示下拉刷新的进度条
                    tipDialog.show();
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(tipDialog::dismiss)
                //使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))
                .subscribe(new ErrorHandleSubscriber<CommonData<Map>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<Map> commonData) {
                        if (commonData.isResult()) {
                            mRootView.update();
                        } else {
                            mRootView.showMessage(commonData.getMessage());
                        }
                    }
                });
    }

    public void getClassByUser() {
        Map<String, Object> map = new LinkedHashMap<>();
        map.put("userId", SPUtils.getInstance().getString(Constants.USERID));
        mModel.getClassByUser(map)
                .subscribeOn(Schedulers.io())
                .doOnSubscribe(disposable -> {
                    mRootView.showLoading();//显示下拉刷新的进度条
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .doFinally(() -> {
                    mRootView.hideLoading();//隐藏下拉刷新的进度条
                })
                .compose(RxLifecycleUtils.bindToLifecycle(mRootView))//使用 Rxlifecycle,使 Disposable 和 Activity 一起销毁
                .subscribe(new ErrorHandleSubscriber<CommonData<List<MineClassData>>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<List<MineClassData>> data) {
                        if (data.isResult()) {
                            List<MineClassData> list = new ArrayList<>();
                            if (data.isResult()) {
                                list.addAll(data.getData());
                            }
                            mRootView.getClassData(list);
                        } else {
                            mRootView.showMessage(data.getMessage());
                            if (data.getMessageCode() == 1105404) {
                                mRootView.killMyself();
                            }
                        }
                    }
                });
    }

    public void upload(WorkSubmitData workSubmitData) {
        RxUtil.uploadImage(workSubmitData.getLocalMedia().getPath(), workSubmitData.getUrl(), ArmsUtils.obtainAppComponentFromContext(mRootView.getActivity()).repositoryManager())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ErrorHandleSubscriber<CommonData<UploadData>>(mErrorHandler) {
                    @Override
                    public void onNext(CommonData<UploadData> upload) {
                        if (upload.isResult()) {
                            workSubmitData.setUploadId(upload.getData().getId());
                        }

                    }
                });
    }
}
